package com.itjin.controller;

import com.itjin.model.domain.vo.SearchResultVO;
import com.itjin.model.domain.vo.HotSearchVO;
import com.itjin.model.result.Result;
import com.itjin.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/search")
@Tag(name = "搜索控制器")
@Slf4j
public class SearchController {

  @Resource
  private SearchService searchService;

  /**
   * 综合搜索
   */
  @GetMapping
  @Operation(summary = "综合搜索")
  public Result<SearchResultVO> search(@RequestParam String keyword, @RequestParam Integer userId) {
    try {
      if (keyword == null || keyword.trim().isEmpty()) {
        return Result.failure(400, "搜索关键词不能为空");
      }
      SearchResultVO result = searchService.search(keyword, userId);
      return Result.success(result);
    } catch (Exception e) {
      log.error("搜索失败", e);
      return Result.failure(500, "搜索失败: " + e.getMessage());
    }
  }

  /**
   * 获取热门搜索
   */
  @GetMapping("/hot")
  @Operation(summary = "获取热门搜索")
  public Result<List<HotSearchVO>> getHotSearches() {
    try {
      List<HotSearchVO> hotSearches = searchService.getHotSearches();
      return Result.success(hotSearches);
    } catch (Exception e) {
      log.error("获取热门搜索失败", e);
      return Result.failure(500, "获取热门搜索失败: " + e.getMessage());
    }
  }

  /**
   * 获取用户搜索历史
   */
  @GetMapping("/history/{userId}")
  @Operation(summary = "获取用户搜索历史")
  public Result<List<String>> getUserSearchHistory(@PathVariable Integer userId) {
    try {
      List<String> history = searchService.getUserSearchHistory(userId);
      return Result.success(history);
    } catch (Exception e) {
      log.error("获取搜索历史失败", e);
      return Result.failure(500, "获取搜索历史失败: " + e.getMessage());
    }
  }

  /**
   * 清除用户搜索历史
   */
  @DeleteMapping("/history/{userId}")
  @Operation(summary = "清除用户搜索历史")
  public Result<Boolean> clearUserSearchHistory(@PathVariable Integer userId) {
    try {
      boolean success = searchService.clearUserSearchHistory(userId);
      return success ? Result.success(true) : Result.failure(400, "清除搜索历史失败");
    } catch (Exception e) {
      log.error("清除搜索历史失败", e);
      return Result.failure(500, "清除搜索历史失败: " + e.getMessage());
    }
  }
}
